package org.ascollada.core
{
	import flash.errors.IllegalOperationError;
	
	import org.ascollada.core.ns.collada;
	
	public class DaeMesh extends DaeElement
	{
		use namespace collada;
		
		public var vertices :Array;
		public var primitives :Array;
		public var vertexChannels :Array;
		
		/**
		 * 
		 */ 
		public function DaeMesh(document:DaeDocument, element:XML=null)
		{
			super(document, element);
		}
		
		/**
		 * 
		 */ 
		public override function destroy():void
		{
			super.destroy();
			if(this.primitives)
			{
				for each(var primitive:DaePrimitive in this.primitives)
					primitive.destroy();
				this.primitives = null;
			}	
			this.vertices = null;
		}
		
		/**
		 * 
		 */ 
		public override function read(element:XML):void
		{
			super.read(element);
			
			var v :XML = element.vertices[0];
			
			if(!v || !v.input[0])
			{
				throw new IllegalOperationError("Invalid or missing <vertices> element!");
			}
			
			var primitive :XML;
			var vinput :DaeInput = new DaeInput(this.document, v.input[0]);

			if(this.document.animatables[vinput.source] is Array)
			{
				var src : DaeSource = document.sources[ vinput.source ];
				src.channels = document.animatables[vinput.source];
				this.vertexChannels = document.animatables[vinput.source];
			}
			else
			{
				this.vertexChannels = null;
			}
			
			this.vertices = this.document.sources[vinput.source].data;
			this.primitives = new Array();
			
			for each(primitive in element.triangles)
			{
				this.primitives.push(new DaePrimitive(this.document, this, primitive));
			}
			
			for each(primitive in element.polylist)
			{
				this.primitives.push(new DaePrimitive(this.document, this, primitive));
			}
			
			for each(primitive in element.polygons)
			{
				this.primitives.push(new DaePrimitive(this.document, this, primitive));
			}
		}
	}
}